const Koa = require("koa");
const app = new Koa();
const Router = require("koa-router");
const router = new Router();
const koaBody = require("koa-body");

app.use(koaBody());

//博客的创建

var myBlogs = new Array();
router.post("/blog/createBlog", ctx => {
  const id = ctx.request.body.id;
  const author = ctx.request.body.author;
  const title = ctx.request.body.title;
  const content = ctx.request.body.content;
  var blog = createBlog(id, author, title, content);
//   console.log(blog.id);
  ctx.body = JSON.stringify(blog);
});

//博客的删除
 router.post("/blog/deleteBlog",ctx=>{
       const id=ctx.request.body.id;
       var blog=deleteBlog(id);
       ctx.body=JSON.stringify(blog);
 });

 //get Blog
 router.get("/blog/getBlog",ctx=>{
       ctx.body=JSON.stringify(myBlogs);
 });

function createBlog(id, author, title, content) {
  var blog = new Object;
  blog.id = id;
  blog.title = title;
  blog.author = author;
  blog.content = content;
  myBlogs[myBlogs.length] = blog;

  return blog;
}

function deleteBlog(id){
    var myBlogs2=new Array();
    for( var i=0,j=0;i<myBlogs.length;i++){
        if(myBlogs[i].id!=id){
            myBlogs2[j]=myBlogs[i];
            j++;
        }
    }
    myBlogs=myBlogs2;
    return myBlogs;
}
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);
